package com.huaxin.common.jpush;

import android.app.ActivityManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import com.huaxin.common.R;
import com.huaxin.common.tools.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class HxJPushReceiver extends BroadcastReceiver {
    private static final String TAG = "xxx==HxJPushReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            String action = intent.getAction();
            if (JPushInterface.ACTION_REGISTRATION_ID.equals(action)) {
                String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                Log.e(TAG, "[MyReceiver] 接收Registration Id : " + regId);
                //send the Registration Id to your server...
            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(action)) {
                JPushManager.receivedCustomMsg(bundle);
                Log.e(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
                //自定义通知消息
                // notifyNotification(context,bundle);

            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(action)) {

                Log.e(TAG, "[MyReceiver] 接收到推送下来的通知");
                int notificationId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
                JPushManager.receivedNotificationMsg(bundle);

            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(action)) {
                Log.e(TAG, "[MyReceiver] 用户点击打开了通知");
                openNotification(context, bundle);
                JPushManager.notificationClicked(bundle);

            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(action)) {
                Log.e(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(action)) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                Log.w(TAG, "[MyReceiver]" + action + " connected state change to " + connected);
            } else {
                Log.e(TAG, "[MyReceiver] Unhandled intent - " + action);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 自定义消息通知栏显示 及点击监听
     *
     * @param context
     * @param bundle
     */
    private void notifyNotification(Context context, Bundle bundle) {
        String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        Log.e(TAG, message + "   " + extras);
        Log.e(TAG, "bundle=" + printBundle(bundle));

        int type = -1;
        //获取NotificationManager实例
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        //通知栏点击广播监听
        Intent intentClick = new Intent(context, NotificationBroadcastReceiver.class);
        intentClick.setAction("notification_clicked");
        intentClick.putExtra(NotificationBroadcastReceiver.TYPE, type);
        intentClick.putExtra("MESSAGE", message);
        PendingIntent pendingIntentClick = PendingIntent.getBroadcast(context, 0, intentClick, PendingIntent.FLAG_ONE_SHOT);

        Intent intentCancel = new Intent(context, NotificationBroadcastReceiver.class);
        intentCancel.setAction("notification_cancelled");
        intentCancel.putExtra(NotificationBroadcastReceiver.TYPE, type);
        PendingIntent pendingIntentCancel = PendingIntent.getBroadcast(context, 0, intentCancel, PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.icon_logo)
                .setContentTitle("通知")
                .setContentText(message)
                .setSound(defaultSoundUri)
                .setAutoCancel(true)  //点击后自动cancle掉通知
                .setContentIntent(pendingIntentClick)
                .setDeleteIntent(pendingIntentCancel);

        notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(type /* ID of notification */, notificationBuilder.build());  //这就是那个type，相同的update，不同add
    }

    /**
     * 打开通知 判断应用是否在前台，是根据字段跳转相应的界面，否启动应用
     *
     * @param context
     * @param bundle
     */
    private void openNotification(Context context, Bundle bundle) {
        //当应用被杀死后，不会收到推送消息  退出登录避免收到推送消息,应该删除Alias
        String alert = bundle.getString(JPushInterface.EXTRA_ALERT);
        // Log.e("jpush", " alert=" + alert);
        Log.e("jpush", "isappAlive notification====" + HxJPushReceiver.isAppAlive(context) + alert);
        if (isAppAlive(context)) {
            if (alert.contains("[审批]")) {
                toTaskWaitDoAct(context);
            } else if (alert.contains("[工单]")) {
                toArrangeTaskAct(context);
            } else {
                toHomeAct(context);
            }
        } else {
            //启动应用
            startApp(context);
        }

    }

    /**
     * topActivity是com.huaxin.hxcloud中的，就表示app运行在前台
     *
     * @return
     */
    public static boolean isAppAlive(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
        String cmpNameTemp = null;
        if (null != runningTaskInfos) {
            cmpNameTemp = runningTaskInfos.get(0).topActivity.toString();
            android.util.Log.e("lwjing", "cmpNameTemp:" + cmpNameTemp);
        }
        if (null == cmpNameTemp)
            return false;
        return cmpNameTemp.contains("com.huaxin.hxcloud");
    }

    /**
     * 启动应用
     *
     * @param context
     */
    public static void startApp(Context context) {
        Intent launchIntent = context.getPackageManager().
                getLaunchIntentForPackage("com.huaxin.hxcloud");
        launchIntent.setFlags(
                Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        Bundle args = new Bundle();
        context.startActivity(launchIntent);
    }

    /**
     * 跳转到HomeActivity
     *
     * @param context
     */
    public static void toHomeAct(Context context) {
        //        String cmdName = "ComponentInfo{com.huaxin.hxcloud/com.huaxin.hxcloud.main.HomeActivity}";  //主界面
        //        if (!isTopActivy(context,cmdName)) {
        //打开自定义的Activity  打开工单activity
        Intent i = new Intent("action_huaxin_homeact");
        i.addCategory("action_huaxin_homeact");
        //如果Task栈中有MainActivity的实例，就会把它移到栈顶，把在它之上的Activity都清理出栈，
        //如果Task栈不存在MainActivity实例，则在栈顶创建
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(i);
        //        }
    }

    /**
     * 待办审批界面
     *
     * @param context
     */
    public static void toTaskWaitDoAct(Context context) {
        String cmdName = "ComponentInfo{com.huaxin.hxcloud/com.huaxin.hxcloud.activity.HxTaskWaitDoActivity}";  //待办列表界面
        if (!isTopActivy(context, cmdName)) {
            //打开自定义的Activity  打开工单activity
            Intent i = new Intent("action_huaxin_taskwaitdo");
            //设置 Intent 的动作为清单中指定的action
            i.addCategory("action_huaxin_taskwaitdo");
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        }
    }

    /**
     * 跳转工单界面
     *
     * @param context
     */
    public static void toArrangeTaskAct(Context context) {
        String cmdName = "ComponentInfo{com.huaxin.hxcloud/com.huaxin.hxcloud.activity.ArrangeTaskListActivity}";  //工单界面
        //判断当前是不是工单界面
        if (!isTopActivy(context, cmdName)) {
            //打开自定义的Activity  打开工单activity
            Intent i = new Intent("action_huaxin_arrangetasklist");
            //设置 Intent 的动作为清单中指定的action
            i.addCategory("action_huaxin_arrangetasklist");
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        }
    }

    /**
     * 检测activity是否在栈顶
     *
     * @return
     */
    public static boolean isTopActivy(Context context, String cmdName) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
        String cmpNameTemp = null;
        if (null != runningTaskInfos) {
            cmpNameTemp = runningTaskInfos.get(0).topActivity.toString();
            android.util.Log.e("lwjing", "cmpNameTemp:" + cmpNameTemp);
        }
        if (null == cmpNameTemp)
            return false;
        return cmpNameTemp.equals(cmdName);
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }
                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();
                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }
}
